<?php

namespace App\Services\Sms;

use App\Commons\CommonConstant;
use App\Services\ServiceBase;

// 华为云短信发送
// https://support.huaweicloud.com/msgsms/index.html
// https://support.huaweicloud.com/api-msgsms/sms_05_0001.html
class HuaweiSmsService extends ServiceBase
{
    public function __construct()
    {
        parent::__construct();
        require_once base_path('extend/huawei-sms/signer.php');
    }

    public function sendPhoneCode($phone, $code)
    {
        $config_name = 'normal';
        $config = CommonConstant::HUAWEI_SMS_CONFIG_LIST[$config_name];

        $signer = new \Signer();
        $signer->Key = $config['appkey'];
        $signer->Secret = $config['appsecret'];

        $headers = [
            'content-type' => 'application/x-www-form-urlencoded',
        ];

        $body = [
            'from'          => $config['sender'],
            'to'            => $phone,
            'templateId'    => $config['template_id'],
            'templateParas' => "[{$code}]",
        ];
        $body = http_build_query($body);

        $url = $config['appurl'];
        $req = new \Request('POST', "{$url}/sms/batchSendSms/v1");
        $req->headers = $headers;
        $req->body = $body;

        $curl = $signer->Sign($req);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
        curl_setopt($curl, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);

        $response = curl_exec($curl);
        $status = curl_getinfo($curl, CURLINFO_HTTP_CODE);
        curl_close($curl);

        if ($status != 200) {
            return false;
        }

        $response = json_decode($response, true);
        if ($response['code'] != '000000') {
            return false;
        }

        return true;
    }
}
